/*
 *  Copyright (c) Skrumtious
 */
package com.skrumtious.backend.persistence;

import java.sql.Timestamp;
import java.util.UUID;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.skrumtious.util.DateUtil;

/**
 * Base class for all persistables
 * 
 * @author Tony
 *
 */
@Entity
@MappedSuperclass
public class PersistenceObject {

	/**
	 * The primary key
	 */
	@Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
	private Key key;
	
	@Column(name = "CREATION_TIME")
	private Timestamp creationTime;
	
	@Column(name = "MOD_TIME")
	private Timestamp modTime;
	
	/**
	 * @param id
	 */
	public PersistenceObject(long id) {
		this.key = KeyFactory.createKey(getClass().getSimpleName(), id);
	}
	
	/**
	 */
	public PersistenceObject() {
		this(UUID.randomUUID().getLeastSignificantBits());
	}
	
	/**
	 * Sets default properties for an insert
	 */
	@PrePersist
	protected void prePersist() {
		this.creationTime = DateUtil.now();
		this.modTime = DateUtil.now();
	}
	
	/**
	 * Sets default properties for an update
	 */
	@PreUpdate
	protected void preUpdate() {
		this.modTime = DateUtil.now();
	}
	
	/*
	 * (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return this.key.toString();
	}
	
	/**
	 * @return the creationTime
	 */
	public Timestamp getCreationTime() {
		return creationTime;
	}
	
	/**
	 * @return the modTime
	 */
	public Timestamp getModTime() {
		return modTime;
	}
	
	/**
	 * @return the key
	 */
	public Key getKey() {
		return key;
	}
	
	/**
	 * Gets the unique id
	 * @return
	 */
	public long getId() {
		return this.key.getId();
	}
}
